import { Decimal } from 'decimal.js';
import { TableColumnCtx } from 'element-plus';

export const getSummaryMethod = (option: {
  list?: string[];
  exclude?: boolean;
  customMethod?: (values: number[], column: TableColumnCtx<any>) => number | string;
  sumText?: string;
}) => {
  const { list = [], exclude = false, customMethod, sumText = '合计' } = option;
  return (param: { columns: TableColumnCtx<any>[]; data: any[] }) => {
    const { columns, data } = param;
    const sums: string[] = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = sumText;
      } else if (exclude ? !list.includes(column.property) : list.includes(column.property)) {
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => Number.isNaN(value))) {
          sums[index] = customMethod
            ? customMethod(values, column).toString()
            : values
                .reduce((prev, curr) => {
                  return Decimal.add(prev, curr).toNumber();
                }, 0)
                .toString();
        } else {
          sums[index] = '-';
        }
      } else {
        sums[index] = '';
      }
    });
    return sums;
  };
};
